<?php
/**
 * The following code, none of which has BUG.
 *
 * @author: BD<657306123@qq.com>
 * @date: 2019/11/20 15:05
 */
declare (strict_types = 1);

namespace app\common\service;

class SafeHandle{

	/**
	 * 模型设置器（id数组转字符串）
	 *
	 * @param array|string $array
	 * @param string       $format
	 * @return string
	 */
	public static function idArrayToString(array $array, $format = 'intval'):string{
		//先转换为数组，进行安全过滤
		if(!is_array($array)) $array = explode(",", $array);

		//去除为空
		$array = array_filter($array);

		//安全过滤
		if($format){
			$array = array_map($format, $array);
		}

		//去除重复
		$array = array_unique($array);

		//再次转换为字符串
		return implode(",", $array);
	}

	/**
	 * 获取安全的ID列表
	 *
	 * @param array|string $str
	 * @param string       $format
	 * @param bool         $filterZero
	 * @return array
	 */
	public static function idStringToArray(string $str, $format = 'intval', bool $filterZero = true):array{
		$str = is_string($str) ? explode(",", $str) : $str;
		$str = is_array($str) ? $str : [$str];
		$str = array_filter($str);
		if($format == '') return $str;

		foreach($str as $k => &$v){
			if('intval' == $format){
				$v = intval($v);
				if($filterZero && $v == 0) unset($str[$k]);
			}elseif('floatval' == $format){
				$v = floatval($v);
				if($filterZero && $v == 0) unset($str[$k]);
			}elseif('boolval' == $format){
				$v = boolval($v);
			}elseif('long2ip' == $format){
				$v = long2ip($v);
				if($filterZero && $v == 0) unset($str[$k]);
			}
		}
		unset($v);

		return array_values($str);
	}
}
